package com.pyue.eam.app.handler;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pyue.eam.app.api.dto.AppUserInfo;
import com.pyue.eam.app.api.entity.AppSocialDetails;
import com.pyue.eam.app.api.entity.AppUser;
import com.pyue.eam.app.mapper.AppSocialDetailsMapper;
import com.pyue.eam.app.service.AppUserService;
import com.pyue.eam.common.core.constant.SecurityConstants;
import com.pyue.eam.common.core.constant.enums.LoginTypeEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author eam
 * @date 2019年11月02日
 * <p>
 * 微信小程序
 */
@Slf4j
@Component("APP-MINI")
@AllArgsConstructor
public class MiniAppLoginHandler extends AbstractLoginHandler {
    private final AppUserService appUserService;
    private final AppSocialDetailsMapper appSocialDetailsMapper;

    /**
     * 小程序登录传入code
     * <p>
     * 通过code 调用qq 获取唯一标识
     */
    @Override
    public IdentifyDto identify(String code) {
        AppSocialDetails condition = new AppSocialDetails();
        condition.setType(LoginTypeEnum.MINI_APP.getType());
        AppSocialDetails socialDetails = appSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));

        String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL, socialDetails.getAppId(),
                socialDetails.getAppSecret(), code);
        String result = HttpUtil.get(url);
        log.debug("微信小程序响应报文:{}", result);

        return IdentifyDto.builder()
                .openid(JSONUtil.parseObj(result).get("openid").toString())
                .unionId(JSONUtil.parseObj(result).get("unionid").toString())
                .build();
    }

    /**
     * openId 获取用户信息
     */
    @Override
    public AppUserInfo info(IdentifyDto identify) {
        AppUser user = appUserService.getOne(Wrappers.<AppUser>query().lambda().eq(AppUser::getWxOpenid, identify.getOpenid()));

        if (user == null) {
            log.info("微信小程序未绑定:{},创建新的用户", identify.getOpenid());
            return createAndSaveAppUserInfo(identify);
        }
        return appUserService.findUserInfo(user);
    }

    /**
     * 绑定逻辑
     *
     * @param user     用户实体
     * @param identify 渠道返回唯一标识
     * @return
     */
    @Override
    public Boolean bind(AppUser user, IdentifyDto identify) {
        user.setWxOpenid(identify.getOpenid());
        user.setUnionId(identify.getUnionId());
        appUserService.updateById(user);
        return true;
    }

    private AppUserInfo createAndSaveAppUserInfo(IdentifyDto identify) {
        AppUser appUser = new AppUser();
        appUser.setWxOpenid(identify.getOpenid());
        appUser.setUnionId(identify.getUnionId());
        appUser.setCreateTime(LocalDateTime.now());
        appUser.setUpdateTime(LocalDateTime.now());
        appUser.setUsername(identify.getOpenid());
        appUser.setCreateBy("");
        appUser.setUpdateBy("");
        appUserService.saveOrUpdate(appUser, Wrappers.<AppUser>lambdaQuery().eq(AppUser::getUsername, identify.getOpenid()));

        AppUserInfo appUserDTO = new AppUserInfo();
        appUserDTO.setAppUser(appUser);
        return appUserDTO;
    }

}
